// 用户路由
import express from "express";
import fs from "node:fs";
import multer from "multer";
import path from "path";
import { list, registers, login, update, remove, avatar } from "../controller/userController.js";
import { registerValidator, loginValidator, updateValidator } from "../middleware/validator/userValidator.js";
import { authMiddleware } from "../utils/jwt.js";
import { randomUUID } from "crypto";
import config from "../config/config.default.js";

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 确保目录存在
    fs.mkdirSync(config.avatarPath, { recursive: true });
    cb(null, config.avatarPath);
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname);
    cb(null, `${randomUUID()}${ext}`);
  },
});

const router = express.Router();
const upload = multer({ storage: storage });
router
  .get("/list", authMiddleware, list)
  .post("/registers", registerValidator, registers)
  .post("/login", loginValidator, login)
  .post("/avatar", authMiddleware, upload.single("avatar"), avatar)
  .put("/", authMiddleware, updateValidator, update)
  .delete("/", remove);

export default router;

